import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:reactive_forms/reactive_forms.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/card_wrap.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/select_phone_widget.dart';
import 'package:yt_devops/components/yt_button.dart';
import 'package:intl/intl.dart';
import 'package:yt_devops/components/yt_form/utils/form_widget_utils.dart';
import 'package:yt_devops/components/yt_form/value_accessors/poi_value_accessors.dart';
import 'package:yt_devops/components/yt_form/widgets/form_text_field.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_bruno_date_picker.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_bruno_input_text.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_map_pick.dart';
import 'package:yt_devops/components/yt_form/widgets/reactive_text_select.dart';
import 'package:yt_devops/model/amap_poi.dart';
import 'package:yt_devops/model/install_provider_model.dart';
import 'package:yt_devops/model/user_model.dart';
import 'package:yt_devops/pages/common/select_page/select_page_model.dart';
import 'package:yt_devops/resources/resources.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/constants/time_formated.dart';
import 'package:yt_devops/utils/enums.dart';
import 'package:yt_devops/utils/toast_utils.dart';
import 'create_install_task_controller.dart';

class CreateInstallTaskPage extends GetView<CreateInstallTaskController> {
  CreateInstallTaskPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        child: Scaffold(
          resizeToAvoidBottomInset: true,
          appBar: AppBarWidget.defaultAppBar(controller.title),
          body: GetBuilder<CreateInstallTaskController>(
            builder: (controller) => ReactiveFormBuilder(
                onWillPop: () async {
                  if (FocusScope.of(context).hasFocus) {
                    FocusScope.of(context).unfocus;
                  }
                  return true;
                },
                form: controller.buildForm,
                builder: (context, form, child) {
                  controller.form = form;

                  return SizedBox(
                      child: ListView(
                    children: [
                      CardWrap(
                        padding: EdgeInsets.only(left: 7.w, right: 16.w),
                        child: Column(children: [
                          FormTextField(
                              formControlName: 'siteName',
                              requireStar: true,
                              style: TextStyles.f16,
                              title: ResKey.siteName.tr,
                              validationMessages: {
                                'required': (error) => ResKey.enterSiteName.tr
                              }),
                          FormTextField(
                            formControlName: 'name',
                            validationMessages: {
                              'required': (error) =>
                                  ResKey.plseEnterInstallationTitle.tr
                            },
                            requireStar: true,
                            style: TextStyles.f16,
                            title: ResKey.installTitle.tr,
                          ),
                          ReactiveBrunoTextInput(
                            formControlName: 'content',
                            title: ResKey.installationDescription.tr,
                            validationMessages: {
                              'required': (error) =>
                                  ResKey.plsEnterInstallDescription.tr
                            },
                            requiredStar: true,
                            showType: ShowType.page,
                            bgColor: Colour.backgroundColor,
                            minHeight: 120.h,
                            minLines: 4,
                          ),
                          ReactiveTextSelect<InstallProviderModel,
                              InstallProviderModel>(
                            formControlName: 'orgId',
                            validationMessages: {
                              'required': (error) => ResKey.installManuTips.tr
                            },
                            title: ResKey.installManu.tr,
                            requireStar: true,
                            value: (InstallProviderModel? v) =>
                                v?.orgName ?? '',
                            onChange: () {
                              form.controls['handlerBy']?.value = null;
                            },
                            selectPageProp:
                                SelectPageProp<InstallProviderModel>(
                              ResKey.installManu.tr,
                              getIdByKey: (model) => model.orgId,
                              getNameKey: (model) => model.orgName ?? '',
                              searchKey: 'orgName',
                              isSearch: true,
                              initSelectValues:
                                  form.controls['orgId']?.value != null
                                      ? [
                                          form.controls['orgId']!.value
                                              as InstallProviderModel
                                        ]
                                      : [],
                              service: (params) => controller.services
                                  .getInstallProvideList({
                                'current': params.pageNum,
                                'pageSize': params.pageSize,
                                ...params.extra ?? {}
                              }, (p0) => false),
                            ),
                          ),
                          ReactiveTextSelect<UserModel, UserModel>(
                            formControlName: 'handlerBy',
                            validationMessages: {
                              'required': (error) =>
                                  ResKey.plsSelectInstallPerson.tr
                            },
                            title: ResKey.installer.tr,
                            requireStar: true,
                            value: (v) => v?.userName ?? '',
                            beforeTap: () {
                              if (form.controls['orgId']?.value == null) {
                                TotastUtils.tip(context,
                                    title: ResKey.plsSelectInstallPerson.tr);
                                return false;
                              } else {
                                return true;
                              }
                            },
                            selectPageProp: SelectPageProp<UserModel>(
                              ResKey.installer.tr,
                              getIdByKey: (model) => model.userId,
                              getNameKey: (model) => model.userName ?? '',
                              searchKey: 'userName',
                              isSearch: true,
                              initSelectValues:
                                  form.controls['handlerBy']?.value != null
                                      ? [
                                          form.controls['handlerBy']!.value
                                              as UserModel
                                        ]
                                      : [],
                              service: (params) =>
                                  controller.services.getInstallerList({
                                'current': params.pageNum,
                                'pageSize': params.pageSize,
                                'orgId': form.controls['orgId']?.value == null
                                    ? null
                                    : (form.controls['orgId']?.value
                                            as InstallProviderModel)
                                        .orgId,
                                ...params.extra ?? {}
                              }, (p0) => false),
                            ),
                          ),
                          FormTextField(
                            formControlName: 'userName',
                            validationMessages: {
                              'required': (error) =>
                                  ResKey.selectCustomerName.tr
                            },
                            requireStar: true,
                            style: TextStyles.f16,
                            title: ResKey.customerName.tr,
                          ),
                          FormTextField(
                            formControlName: 'phone',
                            validationMessages: {
                              'required': (error) => ResKey.requiredPhoneTip.tr
                            },
                            keyboardType: TextInputType.phone,
                            inputFormatters: [],
                            requireStar: true,
                            style: TextStyles.f16,
                            title: ResKey.contactNumber.tr,
                          ),
                          ReactiveBrunoDatePicker(
                            formControlName: 'timeOfAppointment',
                            pickerMode: BrnDateTimePickerMode.datetime,
                            dateFormat: 'yyyy,MM,dd,HH:mm',
                            builder: (context, picker, child) {
                              return ReactiveTextSelect<DateTime, String>(
                                formControlName: 'timeOfAppointment',
                                validationMessages: {
                                  'required': (error) =>
                                      ResKey.selectAppointTime.tr
                                },
                                style: TextStyles.f16,
                                requireStar: true,
                                title: ResKey.appointmentTime.tr,
                                onTap: (t) => picker.showPicker(),
                                valueAccessor: DateTimeValueAccessor(
                                    dateTimeFormat: DateFormat(
                                        TimeFormated.dateTimeFromated)),
                              );
                            },
                            minDateTime: DateTime.now(),
                          ),
                          ReactiveTextSelect<MapType, MapType>(
                            formControlName: 'map',
                            requireStar: true,
                            title: ResKey.mapType.tr,
                            value: (v) => v?.label ?? '',
                            onChange: () => controller.update(),
                            selectPageProp: SelectPageProp<MapType>(
                              ResKey.mapType.tr,
                              pickType: PickType.picker,
                              getIdByKey: (model) => model.value,
                              getNameKey: (model) => model.label,
                              isSearch: false,
                              list: MapType.values,
                              initSelectValues:
                                  form.controls['map']?.value != null
                                      ? [form.controls['map']!.value as MapType]
                                      : [],
                            ),
                          ),
                          ReactiveMapPicker(
                              formControlName: 'address',
                              mapType: form.controls['map']?.value as MapType,
                              builder: (context, picker, child) {
                                Widget suffix =
                                    Image.asset(ImageAssets.iconDingwei);

                                if (picker.value == null) {
                                  suffix = FormWidgetUtils.getRightArrowIcon();
                                }

                                return ReactiveTextSelect<AmapPoi, String>(
                                  onTap: (_) {
                                    picker.showPicker();
                                  },
                                  valueAccessor: PoiValueAccessor(),
                                  formControlName: 'address',
                                  requireStar: true,
                                  title: ResKey.customerAddress.tr,
                                  style: TextStyles.f14,
                                  maxLines: 2,
                                  minLines: 1,
                                  textAlignVertical: TextAlignVertical.center,
                                  decoration: InputDecoration(
                                    suffixIcon: suffix,
                                  ),
                                );
                              })
                        ]),
                      ),
                      CardWrap(
                        padding: EdgeInsets.only(left: 7.w, right: 16.w),
                        child: ReactiveBrunoTextInput(
                          padding: EdgeInsets.only(left: 12.w),
                          formControlName: 'remark',
                          title: ResKey.siteBaseInfoRemark.tr,
                          autoFocus: false,
                        ),
                      ),
                      ReactiveFormConsumer(
                        builder: (context, formGroup, child) => CardWrap(
                          child: SelectPhotoWidget(
                              backgroundColor: Colors.transparent,
                              form.controls['descPicUrl']!.value
                                  as List<String>,
                              true,
                              3,
                              decString: ResKey.siteBaseInfoLimitPictures3.tr,
                              titleString: ResKey.imageAttachment.tr,
                              (List<String> list) {
                            // controller.update();
                          }),
                        ),
                      ),
                      ReactiveFormConsumer(
                        builder: (context, form, child) => SafeArea(
                          child: Container(
                            color: Colour.white,
                            margin: EdgeInsets.only(top: 10.h),
                            padding: EdgeInsets.symmetric(
                                horizontal: 16.w, vertical: 16.h),
                            child: YtButton(
                              enabled: form.valid,
                              text: ResKey.submit.tr,
                              onPress: () {
                                controller.commit(form);
                              },
                            ),
                          ),
                        ),
                      ),
                    ],
                  ));

                  // ),
                }),
          ),
        ));
  }
}
